package security

import (
	"net/http"
	"regexp"
)

// WAFRule 定义WAF规则
type WAFRule struct {
	Pattern string `yaml:"pattern"`
	Action  string `yaml:"action"` // allow/deny
	Path    string `yaml:"path"`
	regex   *regexp.Regexp
}

// WAF Web应用防火墙
type WAF struct {
	rules []*WAFRule
}

func NewWAF() *WAF {
	return &WAF{
		rules: make([]*WAFRule, 0),
	}
}

func (w *WAF) AddRule(rule *WAFRule) error {
	regex, err := regexp.Compile(rule.Pattern)
	if err != nil {
		return err
	}
	rule.regex = regex
	w.rules = append(w.rules, rule)
	return nil
}

func (w *WAF) IsAllowed(r *http.Request) bool {
	for _, rule := range w.rules {
		if rule.regex.MatchString(r.URL.Path) {
			return rule.Action == "allow"
		}
	}
	return true // 默认允许
}
